// token 键定义
const accessTokenKeyLocalStorage = "token";
const refreshAccessTokenKeyLocalStorage = `Refresh-Token`;

// 清除 token
const clearAccessTokens = () => {
  window.localStorage.removeItem(accessTokenKeyLocalStorage);
  window.localStorage.removeItem(refreshAccessTokenKeyLocalStorage);
};

/**
 * 解密 JWT token 的信息
 * @param token jwt token 字符串
 * @returns <any>object
 */
export function decryptJWT(token?: string): any {
  if (!token) return undefined;
  try {
    const newToken = token
      ?.replace(/_/g, "/")
      .replace(/-/g, "+")
      .replace("Bearer ", "");
    const json = decodeURIComponent(
      escape(window.atob(newToken!.split(".")[1]))
    );
    return JSON.parse(json);
  } catch (error) {
    console.log("error", error);
    return undefined;
  }
}

function storeAuthentication(accessToken: string, refreshToken: string): void {
  if (decryptJWT(accessToken)) {
    window.localStorage.setItem(accessTokenKeyLocalStorage, accessToken);
    window.localStorage.setItem(
      refreshAccessTokenKeyLocalStorage,
      refreshToken
    );
  }
}
/**
 * 检查并存储授权信息
 * @param res 响应对象
 */
function checkAndStoreAuthentication(res: Response): void {
  // 读取响应报文头 token 信息
  const accessToken = res.headers.get("Access-Token");
  const refreshToken = res.headers.get("X-Access-Token");

  // 判断是否是无效 token
  if (accessToken === "invalid_token") {
    clearAccessTokens();
    return;
  }
  if (accessToken && refreshToken)
    storeAuthentication(accessToken, refreshToken);
}

/**
 * 将 JWT 时间戳转换成 Date
 * @description 主要针对 `exp`，`iat`，`nbf`
 * @param timestamp 时间戳
 * @returns Date 对象
 */
export function getJWTDate(timestamp: number): Date {
  return new Date(timestamp * 1000);
}
export function getJWT(): Record<string, any> {
  const accessToken = window.localStorage.getItem(accessTokenKeyLocalStorage);
  if (accessToken) {
    return decryptJWT(accessToken);
  }
  return {};
}
export function getAccesstoken(): string | null {
  return window.localStorage.getItem(accessTokenKeyLocalStorage);
}
export function getRefreshToken(): string | null {
  return window.localStorage.getItem(refreshAccessTokenKeyLocalStorage);
}
export function getExpireDate(): Date {
  const jwt = getJWT();
  return new Date(jwt.exp * 1000);
}

export function getIsExpired() {
  const expireDate = getExpireDate();
  return new Date() >= expireDate;
}

export default {
  storeAuthentication,
  clearAccessTokens,
  getJWT,
  getJWTDate,
  getAccesstoken,
  getRefreshToken,
  checkAndStoreAuthentication,
  getExpireDate,
  getIsExpired,
};
